<template>
  <s-layout :title="store?.name || '产品列表'">
  <view class="menu-container">
    <!-- 顶部门店信息 -->
    <view class="store-header">
      <view class="store-name">{{ store.name }}</view>
      <view class="store-address">{{ store.address }}</view>
        <view class="store-distance" v-if="storeDistance">距离您{{ storeDistance }}</view>
      <button class="change-store-btn" @click="changeStore">更换门店</button>
    </view>

    <!-- 主体内容 -->
    <view class="main-layout">
      <!-- 左侧分类 -->
        <scroll-view scroll-y class="category-sidebar" :style="{ height: productListHeight + 'px' }">
        <view
          class="category-item"
          v-for="(category, index) in categories"
          :key="category.id"
          :class="{ active: activeCategory === index }"
          @click="selectCategory(index)"
        >
          <text>{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
        <scroll-view scroll-y :scroll-with-animation="true" class="product-list" :style="{ height: productListHeight + 'px' }" :scroll-top="scrollTopVal" @scroll="onProductScroll">
          <!-- <view class="global-category-title">{{ activeTitle }}</view> -->
          <view v-for="(category, index) in categories" :key="category.id" class="product-group">
          <view class="category-title">{{ category.name }}</view>
          <view class="product-card" v-for="product in category.products" :key="product.id" @click="viewProductDetail(product)">
            <image :src="product.image" class="product-image" />
            <view class="product-info">
              <view class="product-name">{{ product.name }}</view>
              <view class="product-price">¥{{ product.price }}</view>
              <button v-if="product.needSpec" class="select-spec-btn" @click.stop="selectSpec(product)">选规格</button>
              <button v-else class="add-cart-btn" @click.stop="addToCartDirectly(product)">+</button>
            </view>
          </view>
        </view>
          <view v-if="cateringStore.cartCount > 0" style="height: 180rpx"></view>
      </scroll-view>
    </view>
    
    <!-- 底部购物车（弹窗打开时隐藏） -->
    <view class="cart-bar" v-if="cateringStore.cartCount > 0 && !cartPopupVisible" @click="showCartDetailPopup">
        <view class="cart-icon-wrapper">
            <uni-icons type="cart" size="30" color="#fff"></uni-icons>
            <view class="cart-badge" v-if="cateringStore.cartCount > 0">{{ cateringStore.cartCount }}</view>
        </view>
        <view class="cart-price">¥{{ Number(cateringStore.cartTotal || 0).toFixed(2) }}</view>
        <button class="checkout-btn" @click.stop="checkout">结算</button>
    </view>
    
    <!-- 购物车详情弹窗 -->
    <uni-popup
        ref="cartPopup"
        type="bottom"
        :mask-click="true"
        @change="onPopupChange"
    >
        <view class="cart-popup-content" @click.stop>
            <view class="cart-popup-header">
                <text>购物车</text>
                <view class="clear-cart-btn" @click="clearCart">
                    <uni-icons type="trash" size="18" color="#999"></uni-icons>
                    <text>清空</text>
                </view>
            </view>
            <scroll-view scroll-y class="cart-items-scroll" v-show="cateringStore.cart.length > 0">
                <view class="cart-item" v-for="item in cateringStore.cart" :key="item.uniqueId">
                    <image :src="item.image" class="item-image" />
                    <view class="item-info">
                        <view class="item-name">{{ item.name }}</view>
                        <view class="item-specs">{{ item.specsText }}</view>
                    </view>
                    <view class="item-price">¥{{ item.price.toFixed(2) }}</view>
                    <view class="item-quantity-control">
                        <button class="control-btn" @click="updateQuantity(item.uniqueId, item.quantity - 1)">-</button>
                        <text class="quantity-text">{{ item.quantity }}</text>
                        <button class="control-btn" @click="updateQuantity(item.uniqueId, item.quantity + 1)">+</button>
                    </view>
                </view>
            </scroll-view>
            <view class="empty-cart" v-show="cateringStore.cart.length === 0">
                购物车还是空的哦～
            </view>
            
            <!-- 底部结算栏（与页面一致样式） -->
            <view class="cart-popup-footer" v-show="cateringStore.cart.length > 0">
                <view class="footer-cart-icon">
                    <uni-icons type="cart" size="30" color="#fff"></uni-icons>
                    <view class="footer-cart-badge" v-if="cateringStore.cartCount > 0">{{ cateringStore.cartCount }}</view>
                </view>
                <view class="footer-total">
                    <text class="total-price">¥{{ Number(cateringStore.cartTotal || 0).toFixed(2) }}</text>
                </view>
                <button class="footer-checkout-btn" @click="checkout">结算</button>
            </view>
        </view>
    </uni-popup>

  </view>
  </s-layout>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, getCurrentInstance, watch } from 'vue';
import sheep from '@/sheep';
import { getProductDetailRoute, getBrandName } from './common/brand-routes.js';

const cateringStore = sheep.$store('catering');
const store = computed(() => cateringStore.storeInfo || {});

const activeCategory = ref(0);
const isCategoryClick = ref(false);
const groupTops = ref([]);
const scrollTopVal = ref(0);
const productListHeight = ref(0);

const categories = ref([]);

const activeTitle = computed(() => {
    const idx = activeCategory.value;
    const list = categories.value || [];
    return list[idx] ? list[idx].name : '';
});

const cartPopup = ref(null);
const cartPopupVisible = ref(false);
const isPopupOpen = ref(false);
let manualClosing = false;

let scrollTop = 0;

const storeDistance = ref('');

onMounted(() => {
    loadMenu();
    nextTick(() => {
        measureGroups();
        calcProductListHeight();
    });
    // 图片加载可能影响测量，延迟重测
    setTimeout(() => measureGroups(), 600);
    setTimeout(() => measureGroups(), 1200);
    setTimeout(() => calcProductListHeight(), 600);
    setTimeout(() => calcProductListHeight(), 1200);
    calcStoreDistance();
    // 监听窗口尺寸变化，重新计算可滚动高度
    // #ifdef H5
    if (typeof window !== 'undefined') {
        window.addEventListener('resize', () => {
            calcProductListHeight();
        });
    }
    // #endif
});

function measureGroups() {
    const q = uni.createSelectorQuery();
    q.select('.product-list').boundingClientRect();
    q.selectAll('.product-group').boundingClientRect();
    q.exec(res => {
        const containerRect = res && res[0] ? res[0] : null;
        const groupRects = res && res[1] ? res[1] : [];

        if (containerRect && Array.isArray(groupRects) && groupRects.length > 0) {
            const containerTop = containerRect.top;
            groupTops.value = groupRects.map(r => Math.max(0, r.top - containerTop));
            console.log('Measured group tops (relative to container, page context):', groupTops.value);
        } else {
            groupTops.value = [];
            console.log('Failed to measure group tops (page context).');
        }
    });
}

function h5ForceScroll(top) {
    // #ifdef H5
    try {
        requestAnimationFrame(() => {
            const el = document.querySelector('.product-list .uni-scroll-view') || document.querySelector('.product-list');
            if (el) {
                el.scrollTop = top;
                console.log('h5ForceScroll applied, targetTop:', top, 'actual:', el.scrollTop);
            } else {
                console.log('h5ForceScroll: element not found');
            }
        });
    } catch (e) {
        console.log('h5ForceScroll error:', e && e.message);
    }
    // #endif
}

function calcProductListHeight() {
    try {
        const sys = uni.getSystemInfoSync();
        const winH = sys && sys.windowHeight ? sys.windowHeight : 0;
        const q = uni.createSelectorQuery();
        q.select('.product-list').boundingClientRect();
        q.select('.cart-bar').boundingClientRect();
        q.exec(res => {
            const listRect = res && res[0] ? res[0] : null;
            const barRect = res && res[1] ? res[1] : null;
            if (!listRect) return;
            const barH = barRect ? barRect.height : 0;
            const height = Math.max(200, winH - listRect.top - barH - 10);
            productListHeight.value = Math.floor(height);
            console.log('calcProductListHeight -> winH:', winH, 'listTop:', listRect.top, 'barH:', barH, 'height:', productListHeight.value);
        });
    } catch (e) {}
}

function computeAndScrollTo(index) {
    const q = uni.createSelectorQuery();
    q.select('.product-list').boundingClientRect();
    q.select('.product-list').scrollOffset();
    q.selectAll('.product-group').boundingClientRect();
    q.exec(res => {
        const containerRect = res && res[0] ? res[0] : null;
        const containerScroll = res && res[1] ? res[1] : null;
        const groupRects = res && res[2] ? res[2] : [];
        if (!containerRect || !containerScroll || !groupRects || !groupRects[index]) {
            console.log('computeAndScrollTo: measurement missing');
            isCategoryClick.value = false;
            return;
        }
        const containerTop = containerRect.top;
        const currentScrollTop = containerScroll.scrollTop || 0;
        const targetRect = groupRects[index];
        // 计算：目标分组相对容器的可视区域偏移 + 当前滚动值 = 目标 scrollTop
        let targetTop = Math.max(0, (targetRect.top - containerTop) + currentScrollTop);
        console.log(`computeAndScrollTo -> index: ${index}, targetTop: ${targetTop}, currentScrollTop: ${currentScrollTop}`);
        // 采用 nudge 技术强制触发
        scrollTopVal.value = targetTop + 1;
        nextTick(() => {
            scrollTopVal.value = targetTop;
            // H5 兜底：直接设置真实滚动容器的 scrollTop
            // #ifdef H5
            setTimeout(() => {
                h5ForceScroll(targetTop);
                const q2 = uni.createSelectorQuery();
                q2.select('.product-list').scrollOffset().exec(r2 => {
                    const off = r2 && r2[0] ? r2[0].scrollTop : null;
                    console.log('after force scroll, currentScrollTop:', off);
                });
            }, 30);
            // #endif
        });
        setTimeout(() => {
            isCategoryClick.value = false;
        }, 500);
    });
}

function calcStoreDistance() {
    try {
        const s = store.value || {};
        const rawLat = s.latitude ?? s.lat ?? s.shopLatitude ?? s.shopLat;
        const rawLon = s.longitude ?? s.lon ?? s.lng ?? s.shopLongitude ?? s.shopLng;
        const sLat = rawLat !== undefined && rawLat !== null && rawLat !== '' ? parseFloat(rawLat) : 0;
        const sLon = rawLon !== undefined && rawLon !== null && rawLon !== '' ? parseFloat(rawLon) : 0;
        if (!(sLat && sLon)) return;
        uni.getLocation({
            type: 'gcj02',
            success: (res) => {
                const d = haversine(res.latitude, res.longitude, sLat, sLon);
                storeDistance.value = d < 1 ? `${Math.round(d * 1000)}m` : `${d.toFixed(1)}km`;
            }
        });
    } catch (e) {}
}

function haversine(lat1, lon1, lat2, lon2) {
    const R = 6371;
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) * Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
}

async function loadMenu() {
    if (!store.value || !store.value.id) {
        uni.showToast({ title: '未选择门店', icon: 'error' });
        setTimeout(() => sheep.$router.back(), 1500);
        return;
    }
    
    uni.showLoading({ title: '加载菜单...' });
    try {
        // 优先使用真实 shopId 字段，其次使用 id
        const shopId = store.value.shopId || store.value.id;
        const brandOt = getBrandOt();  // ✅ 获取品牌类型
        
        console.log('【菜单加载】门店ID:', shopId, '品牌类型:', brandOt);
        
        // ✅ 传递品牌类型参数
        const res = await sheep.$api.catering.getMenu(shopId, { ot: brandOt });
        uni.hideLoading();
        
        // 新老接口兼容：可能返回 { code: 0|200, data: [...] }
        const ok = res && (res.code === 0 || res.code === 200);
        if (ok && Array.isArray(res.data)) {
            const srcList = res.data;
            const outCategories = [];
            srcList.forEach(top => {
                if (Array.isArray(top.menuVoList) && top.menuVoList.length > 0) {
                    outCategories.push({
                        id: top.classExtId || top.topHash || top.topName || `top-${outCategories.length}`,
                        name: top.topName || top.cate_name ||top.name || '推荐',
                        products: top.menuVoList.map(p => ({
                            id: p.productId || p.itemNo || p.linkId || (p.relax_goods && (p.relax_goods.kfc_prod_id || p.relax_goods.goods_id)) || `${Math.random()}`,
                            detailId: (p.relax_goods && (p.relax_goods.kfc_relation_id || p.relax_goods.kfc_prod_id)) || p.linkId || p.productId || p.itemNo,
                            rid: p.relax_goods && p.relax_goods.kfc_relation_id,
                            lid: p.linkId,
                            kid: p.relax_goods && p.relax_goods.kfc_prod_id,
                            pidRaw: p.productId || p.itemNo,
                            name: p.showNameCn || p.nameCn || p.title || p.name || p.igName || '',
                            image: p.imageUrl || p.litimgUrl || p.detailImgUrl || p.coverUrl || (p.relax_goods && p.relax_goods.thumbnail) || '',
                            price: p.salePrice || p.priceHead || 0,  // ✅ 优先使用后端自定义售价
                            originalPrice: p.originalPrice || p.price || 0,  // ✅ 保存原价
                            description: p.descCn || p.detail || (p.relax_goods && p.relax_goods.description) || '',
                            menuFlag: p.menuFlag,
                            isMultipleChoice: p.isMultipleChoice,
                            needSpec: p.menuFlag === '1' || p.menuFlag === 'C' || p.isMultipleChoice === '1' || p.isMultipleChoice === 'Y'
                        }))
                    });
                }
                if (Array.isArray(top.childClassList)) {
                    top.childClassList.forEach(child => {
                        // 如果child没有名称，使用父级的topName
                        const childName = child.nameCn || child.topName || top.topName || '分类';
                        outCategories.push({
                            id: child.classExtId || child.topName || child.nameCn || top.topName || `cat-${outCategories.length}`,
                            name: childName,
                            products: Array.isArray(child.menuVoList) ? child.menuVoList.map(p => ({
                                id: p.productId || p.linkId || (p.relax_goods && (p.relax_goods.kfc_prod_id || p.relax_goods.goods_id)) || `${Math.random()}`,
                                detailId: (p.relax_goods && (p.relax_goods.kfc_relation_id || p.relax_goods.kfc_prod_id)) || p.linkId || p.productId,
                                rid: p.relax_goods && p.relax_goods.kfc_relation_id,
                                lid: p.linkId,
                                kid: p.relax_goods && p.relax_goods.kfc_prod_id,
                                pidRaw: p.productId,
                                name: p.showNameCn || p.nameCn || p.igName || '',
                                image: p.imageUrl || (p.relax_goods && p.relax_goods.thumbnail) || '',
                                price: p.salePrice || p.priceHead || 0,  // ✅ 优先使用后端自定义售价
                            originalPrice: p.originalPrice || p.price || 0,  // ✅ 保存原价
                            description: p.descCn || (p.relax_goods && p.relax_goods.description) || '',
                            menuFlag: p.menuFlag,
                            isMultipleChoice: p.isMultipleChoice,
                            needSpec: p.menuFlag === '1' || p.menuFlag === 'C' || p.isMultipleChoice === '1' || p.isMultipleChoice === 'Y'
                        })) : []
                    });
                });
            }
        });
        categories.value = outCategories;
            nextTick(() => measureGroups());
        } else if (ok && res.data && typeof res.data === 'object') {
            const top = res.data;
            const outCategories = [];
            if (Array.isArray(top.menuVoList)) {
                outCategories.push({
                    id: top.classExtId || top.topHash || top.topName || 'top',
                    name: top.topName || '推荐',
                    products: top.menuVoList.map(p => ({
                        id: p.productId || p.linkId || (p.relax_goods && (p.relax_goods.kfc_prod_id || p.relax_goods.goods_id)) || `${Math.random()}`,
                        detailId: (p.relax_goods && (p.relax_goods.kfc_relation_id || p.relax_goods.kfc_prod_id)) || p.linkId || p.productId,
                        rid: p.relax_goods && p.relax_goods.kfc_relation_id,
                        lid: p.linkId,
                        kid: p.relax_goods && p.relax_goods.kfc_prod_id,
                        pidRaw: p.productId,
                        name: p.showNameCn || p.nameCn || p.igName || '',
                        image: p.imageUrl || (p.relax_goods && p.relax_goods.thumbnail) || '',
                        price: p.priceHead || p.price || p.basePrice || (p.relax_goods && (p.relax_goods.promoted_price || p.relax_goods.price)) || 0,
                        description: p.descCn || (p.relax_goods && p.relax_goods.description) || '',
                        menuFlag: p.menuFlag,
                        isMultipleChoice: p.isMultipleChoice,
                        needSpec: p.menuFlag === '1' || p.menuFlag === 'C' || p.isMultipleChoice === '1' || p.isMultipleChoice === 'Y'
                    }))
                });
            }
            if (Array.isArray(top.childClassList)) {
                top.childClassList.forEach(child => {
                    // 如果child没有名称，使用父级的topName
                    const childName = child.nameCn || child.topName || top.topName || '分类';
                    outCategories.push({
                        id: child.classExtId || child.topName || child.nameCn || top.topName || `cat-${outCategories.length}`,
                        name: childName,
                        products: Array.isArray(child.menuVoList) ? child.menuVoList.map(p => ({
                            id: p.productId || p.linkId || (p.relax_goods && (p.relax_goods.kfc_prod_id || p.relax_goods.goods_id)) || `${Math.random()}`,
                            detailId: (p.relax_goods && (p.relax_goods.kfc_relation_id || p.relax_goods.kfc_prod_id)) || p.linkId || p.productId,
                            rid: p.relax_goods && p.relax_goods.kfc_relation_id,
                            lid: p.linkId,
                            kid: p.relax_goods && p.relax_goods.kfc_prod_id,
                            pidRaw: p.productId,
                            name: p.showNameCn || p.nameCn || p.igName || '',
                            image: p.imageUrl || (p.relax_goods && p.relax_goods.thumbnail) || '',
                            price: p.salePrice || p.priceHead || 0,  // ✅ 优先使用后端自定义售价
                            originalPrice: p.originalPrice || p.price || 0,  // ✅ 保存原价
                            description: p.descCn || (p.relax_goods && p.relax_goods.description) || '',
                            menuFlag: p.menuFlag,
                            isMultipleChoice: p.isMultipleChoice,
                            needSpec: p.menuFlag === '1' || p.menuFlag === 'C' || p.isMultipleChoice === '1' || p.isMultipleChoice === 'Y'
                        })) : []
                    });
                });
            }
            categories.value = outCategories;
            nextTick(() => measureGroups());
        } else {
            uni.showToast({ title: '加载菜单失败', icon: 'none' });
            categories.value = [];
        }
    } catch (error) {
        uni.hideLoading();
        console.error('加载菜单失败:', error);
        uni.showToast({ title: '加载菜单失败', icon: 'error' });
        categories.value = [];
    }
}

function changeStore() {
    sheep.$router.back();
}

function selectCategory(index) {
    if (index < 0) return;
    activeCategory.value = index;
    isCategoryClick.value = true;
    computeAndScrollTo(index);
}

function onProductScroll(e) {
    if (isCategoryClick.value) return;
    const y = e.detail.scrollTop || 0;
    if (!groupTops.value || groupTops.value.length === 0) return;
    let currentIndex = 0;
    for (let i = 0; i < groupTops.value.length; i++) {
        if (y >= groupTops.value[i] - 20) {
            currentIndex = i;
        } else {
            break;
        }
    }
    if (activeCategory.value !== currentIndex) {
        activeCategory.value = currentIndex;
    }
}

// 获取品牌类型 (ot)
function getBrandOt() {
    // 优先级1: 从 store 中获取
    if (store.value.ot) {
        console.log('【路由】从 store.ot 获取品牌类型:', store.value.ot);
        return store.value.ot;
    }
    
    // 优先级2: 从 store.orderType 获取
    if (store.value.orderType) {
        console.log('【路由】从 store.orderType 获取品牌类型:', store.value.orderType);
        return store.value.orderType;
    }
    
    // 优先级3: 从 store.type 获取
    if (store.value.type) {
        console.log('【路由】从 store.type 获取品牌类型:', store.value.type);
        return store.value.type;
    }
    
    // 优先级4: 从 cateringStore 直接获取
    if (cateringStore.storeInfo && cateringStore.storeInfo.ot) {
        console.log('【路由】从 cateringStore.storeInfo.ot 获取品牌类型:', cateringStore.storeInfo.ot);
        return cateringStore.storeInfo.ot;
    }
    
    // 优先级5: 从当前页面的 URL 参数获取（如果有）
    const pages = getCurrentPages();
    if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        if (currentPage.options && currentPage.options.ot) {
            console.log('【路由】从页面参数获取品牌类型:', currentPage.options.ot);
            return parseInt(currentPage.options.ot);
        }
    }
    
    // 打印调试信息
    console.warn('【路由】无法获取品牌类型，使用默认值 1 (KFC)');
    console.log('【路由调试】store.value:', JSON.stringify(store.value));
    console.log('【路由调试】cateringStore.storeInfo:', JSON.stringify(cateringStore.storeInfo));
    
    return 1; // 默认 KFC
}

function viewProductDetail(product) {
    // 点击商品卡片：需要选规格则跳转详情页，否则不做任何操作
    if (product.needSpec) {
        const sid = (store.value && (store.value.shopId || store.value.id)) || '';
        const ot = getBrandOt(); // 使用新的获取函数
        // 优先使用 productId，最后才使用 linkId
        const pid = product.pidRaw || product.rid || product.detailId || product.kid || product.id || product.lid;
        
        // 根据品牌类型获取对应的详情页路由
        const detailRoute = getProductDetailRoute(ot);
        const brandName = getBrandName(ot);
        
        console.log(`【${brandName}】跳转商品详情，使用ID:`, pid, '商品:', product.name, '路由:', detailRoute);
        sheep.$router.go(detailRoute, { productId: String(pid || ''), shopId: String(sid || ''), name: product.name });
    }
    // 不需要选规格的商品，点击卡片不做任何操作（只有点+号才加购）
}

function selectSpec(product) {
    const sid = (store.value && (store.value.shopId || store.value.id)) || '';
    const ot = getBrandOt(); // 使用新的获取函数
    // 优先使用 productId，最后才使用 linkId
    const pid = product.pidRaw || product.rid || product.detailId || product.kid || product.id || product.lid;
    
    // 根据品牌类型获取对应的详情页路由
    const detailRoute = getProductDetailRoute(ot);
    const brandName = getBrandName(ot);
    
    console.log(`【${brandName}】选择规格，使用ID:`, pid, '商品:', product.name, '路由:', detailRoute);
    sheep.$router.go(detailRoute, { productId: String(pid || ''), shopId: String(sid || ''), name: product.name });
}

function addToCartDirectly(product) {
    const cartItem = {
        id: product.id,
        name: product.name,
        image: product.image,
        price: product.price,  // ✅ 使用后端自定义售价（已在loadMenu中处理）
        originalPrice: product.originalPrice || product.price,  // ✅ 原价
        selectedSpecs: {},
        specsText: '默认',
        brandOt: getBrandOt(),  // ✅ 保存品牌类型
        shopId: store.value.shopId || store.value.id  // ✅ 保存门店ID
    };
    cateringStore.addToCart(cartItem);
    uni.showToast({
        title: '已加入购物车',
        icon: 'success',
        duration: 1500
    });
    // 不再自动弹出购物车，仅显示提示
}

function checkout() {
    if(cateringStore.cart.length === 0) {
        uni.showToast({title: '购物车是空的哦', icon: 'none'})
        return;
    }
    if (cartPopup.value) {
        manualClosing = true;
        cartPopupVisible.value = false;
        cartPopup.value.close();
    }
    sheep.$router.go('/pages/catering/confirm-order');
    setTimeout(() => { manualClosing = false; }, 500);
}

function showCartDetailPopup() {
    if (cateringStore.cart.length === 0) return;
    
    // 使用 nextTick 确保组件已挂载
    nextTick(() => {
        if (cartPopup.value && typeof cartPopup.value.open === 'function') {
            manualClosing = false;
            cartPopupVisible.value = true; // 打开时隐藏底部栏
            cartPopup.value.open();
        } else {
            console.warn('购物车弹窗组件未就绪:', cartPopup.value);
        }
    });
}

function clearCart() {
    cateringStore.clearCart();
    // 延时关闭避免遮罩层残留
    setTimeout(() => {
        if (cartPopup.value && typeof cartPopup.value.close === 'function') {
            manualClosing = true;
            cartPopupVisible.value = false;
            cartPopup.value.close();
            forceRemoveMask();
            setTimeout(() => { manualClosing = false; }, 400);
        }
    }, 300);
}

// 弹窗状态变化监听
function onPopupChange(e) {
    console.log('弹窗状态变化:', e);
    isPopupOpen.value = e.show;
    cartPopupVisible.value = e.show; // 显示/隐藏页面底部栏
    
    // 遮罩点击关闭后，仅清理遮罩并保持关闭，不再自动重开
    if (!e.show) {
        forceRemoveMask();
        manualClosing = false;
    }
}

// 强制移除遮罩层
function forceRemoveMask() {
    setTimeout(() => {
        // 尝试移除所有可能残留的遮罩层
        const masks = document.querySelectorAll('.uni-mask, .uni-popup__mask, .uni-popup-mask');
        masks.forEach(mask => {
            mask.style.display = 'none';
            mask.remove();
        });
        console.log('已强制清除遮罩层');
    }, 100);
}

function updateQuantity(uniqueId, quantity) {
    cateringStore.updateQuantity(uniqueId, quantity);
    
    // 使用 nextTick 确保 Pinia 状态更新后再检查
    nextTick(() => {
        const remainingItems = cateringStore.cart.length;
        console.log('购物车剩余商品数量:', remainingItems);
        
        // 只有当购物车完全为空时才关闭弹窗
        if (remainingItems === 0) {
            console.log('购物车已空，300ms后关闭弹窗');
            setTimeout(() => {
                if (cartPopup.value && typeof cartPopup.value.close === 'function') {
                    cartPopup.value.close();
                    forceRemoveMask();
                    console.log('购物车弹窗已关闭');
                }
            }, 300);
        } else {
            console.log('购物车还有商品，保持弹窗打开');
            // 若弹窗意外关闭，强制重新打开
            setTimeout(() => {
                if (!isPopupOpen.value && !manualClosing && cartPopup.value && typeof cartPopup.value.open === 'function') {
                    console.log('updateQuantity 触发重开弹窗');
                    cartPopupVisible.value = true;
                    cartPopup.value.open();
                }
            }, 50);
        }
    });
}
</script>

<style lang="scss" scoped>
.menu-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh; // 小程序端使用视口高度，避免计算误差
    position: relative;
    box-sizing: border-box;
    padding-bottom: 160rpx; // 预留底部结算栏空间，避免内容被遮挡
}

.store-header {
    padding: 20rpx 30rpx 30rpx 30rpx;
    background: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    position: relative;
    .store-name {
        font-size: 32rpx;
        font-weight: bold;
    }
    .store-address {
        font-size: 24rpx;
        color: #999;
        margin-top: 6rpx;
        margin-right: 180rpx;
    }
    .store-distance {
        font-size: 22rpx;
        color: #999;
        margin-top: 6rpx;
    }
    .change-store-btn {
        position: absolute;
        top: 20rpx;
        right: 30rpx;
        font-size: 24rpx;
        color: #c7000b;
        border: 1rpx solid #c7000b;
        background: #fff;
        border-radius: 20rpx;
    }
}

.main-layout {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.category-sidebar {
    width: 180rpx;
    background: #f5f5f5;
    .category-item {
        padding: 30rpx 20rpx;
        font-size: 28rpx;
        text-align: center;
        position: relative;
        &.active {
            background: #fff;
            font-weight: bold;
            color: #c7000b;
            &:before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 8rpx;
                height: 40rpx;
                background: #c7000b;
            }
        }
    }
}

.product-list {
    flex: 1;
    background: #fff;
    padding: 20rpx;
    -webkit-overflow-scrolling: touch;
    box-sizing: border-box;
    padding-bottom: 160rpx; // 兜底：再预留一份空间，兼容计算不及时
    .global-category-title {
        position: sticky;
        top: 0;
        z-index: 3;
        background: #fff;
        font-size: 28rpx;
        font-weight: bold;
        padding: 16rpx 0;
        margin: 0 0 10rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
    }
    .product-group {
        margin-bottom: 20rpx;
    }
    .category-title {
        position: static;
        font-size: 28rpx;
        font-weight: bold;
        padding: 16rpx 0;
        margin: 0 0 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
    }
    .product-card {
        display: flex;
        margin-bottom: 40rpx;
        padding: 20rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
        overflow: hidden;
        .product-image {
            width: 180rpx;
            height: 180rpx;
            border-radius: 12rpx;
            margin-right: 24rpx;
            flex-shrink: 0;
        }
        .product-info {
            flex: 1;
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .product-name {
                font-size: 30rpx;
                font-weight: bold;
                line-height: 1.4;
                // 最多显示两行
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                -webkit-box-orient: vertical;
            }
            .product-price {
                font-size: 32rpx;
                color: #c7000b;
                font-weight: bold;
            }
            .select-spec-btn {
                position: absolute;
                bottom: -10rpx;
                right: -10rpx;
                background: #c7000b;
                color: #fff;
                font-size: 24rpx;
                padding: 10rpx 20rpx;
                border-radius: 30rpx;
                line-height: 1;
            }
            .add-cart-btn {
                position: absolute;
                bottom: -10rpx;
                right: -10rpx;
                width: 50rpx;
                height: 50rpx;
                background: #c7000b;
                color: #fff;
                font-size: 36rpx;
                border-radius: 50%;
                line-height: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 0;
            }
        }
    }
}

.cart-bar {
    position: fixed;
    bottom: 0;
    left: 20rpx;
    right: 20rpx;
    height: 100rpx;
    background: #333;
    border-radius: 50rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    // padding-left: 20rpx;
    color: #fff;
    padding-bottom: constant(safe-area-inset-bottom);
    // padding-bottom: env(safe-area-inset-bottom);
    z-index: 9; // 置于内容之上，低于弹窗
    box-sizing: border-box;
    transform: translateZ(0); // 提升层叠，避免抖动
    .cart-icon-wrapper {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        background: #c7000b;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        // top: -20rpx;
        .cart-badge {
            position: absolute;
            top: 10rpx;
            right: 10rpx;
            background: #fff;
            color: #c7000b;
            border-radius: 50%;
            font-size: 20rpx;
            padding: 2rpx 8rpx;
            min-width: 30rpx;
            text-align: center;
        }
    }
    .cart-price {
        font-size: 36rpx;
        font-weight: bold;
        margin-left: 20rpx;
    }
    .checkout-btn {
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 200rpx;
        background: #c7000b;
        color: #fff;
        font-size: 32rpx;
        border-radius: 0 50rpx 50rpx 0;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.cart-popup-content {
    background-color: #fff;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    max-height: 70vh;
    box-sizing: border-box;
    padding-bottom: env(safe-area-inset-bottom);

    .cart-popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        font-size: 32rpx;
        font-weight: bold;
        flex-shrink: 0;

        .clear-cart-btn {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: #999;
            font-weight: normal;
        }
    }

    .cart-items-scroll {
        flex: 1;
        min-height: 200rpx;
        max-height: 500rpx;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }

    .cart-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;

        .item-image {
            width: 120rpx;
            height: 120rpx;
            border-radius: 10rpx;
            margin-right: 20rpx;
        }

        .item-info {
            flex: 1;
            .item-name {
                font-size: 28rpx;
            }
            .item-specs {
                font-size: 22rpx;
                color: #999;
                margin-top: 5rpx;
            }
        }

        .item-price {
            font-size: 28rpx;
            font-weight: bold;
            margin: 0 20rpx;
        }

        .item-quantity-control {
            display: flex;
            align-items: center;
            .control-btn {
                width: 50rpx;
                height: 50rpx;
                line-height: 50rpx;
                text-align: center;
                border-radius: 50%;
                background: #f5f5f5;
                padding: 0;
                font-size: 36rpx;
            }
            .quantity-text {
                margin: 0 20rpx;
                font-size: 28rpx;
            }
        }
    }
    
    .empty-cart {
        text-align: center;
        color: #999;
        padding: 80rpx 0;
    }
    
    .cart-popup-footer {
        position: relative;
        height: 100rpx;
        background: #333;
        border-radius: 50rpx;
        margin: 20rpx -10rpx -10rpx;
        display: flex;
        align-items: center;
        // padding-left: 20rpx;
        flex-shrink: 0;
        // padding-bottom: env(safe-area-inset-bottom);
        box-sizing: border-box;
        
        .footer-cart-icon {
            width: 100rpx;
            height: 100rpx;
            border-radius: 50%;
            background: #c7000b;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            // top: -20rpx;
            margin-right: 10rpx;
            flex-shrink: 0;
            
            .footer-cart-badge {
                position: absolute;
                top: 10rpx;
                right: 10rpx;
                background: #fff;
                color: #c7000b;
                border-radius: 50%;
                font-size: 20rpx;
                padding: 2rpx 8rpx;
                min-width: 30rpx;
                text-align: center;
            }
        }
        
        .footer-total {
            flex: 1;
            display: flex;
            align-items: baseline;
            
            .total-label {
                font-size: 28rpx;
                color: #fff;
            }
            
            .total-price {
                font-size: 36rpx;
                font-weight: bold;
                color: #fff;
                margin-left: 8rpx;
            }
        }
        
        .footer-checkout-btn {
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            width: 200rpx;
            background: #c7000b;
            color: #fff;
            font-size: 32rpx;
            font-weight: normal;
            border-radius: 0 50rpx 50rpx 0;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0;
            line-height: 1;
        }
    }
}
</style>
